<template>

  <div>
    <el-upload
      ref="upload"
      drag
      class="upload-demo"
      action="#"
      :http-request="httpRequest"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="3"
      :on-exceed="handleExceed"
      :on-success="handleFileSuccess"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">限制传输一次不能超过3个文件</div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
    </span>
  </div>


</template>

<script>

import {fileSave} from "@/api/file";

export default {
  name: "upload",
  data() {
    return {
    };
  },
  methods: {
    httpRequest(data){
      /*自定义上传*/

      let formData = new FormData();
      formData.append('file', data.file);
      //使用raw才能正常上传

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }

      fileSave(formData).then(
        res=>{
          if (res.code===0) {
            this.$message({
              type: 'success',
              message: '文件上传成功！'
            })

          } else {
            this.$message({
              /*上传失败*/
              type: 'error',
              message: res.msg
            })

          }
          this.$emit('refresh-me');
        }
      )

    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      //删除已经上传的文件
    },
    handlePreview(file) {
      console.log(file);
      /*点击已经上传时的文件*/
    },
    handleExceed(files, fileList) {
      /*文件超出个数限制时的钩子*/
      this.$message.warning(`当前限制选择 3 个文件，请刷新后重传`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    close(){
      this.$emit('close-me')
    },
    handleFileSuccess(res, file){
      console.log(file)
    }
  }
}
</script>

<style scoped>

</style>
